package com.shike.core.storage;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Data;

import java.io.InputStream;

@Data
public class QiniuStorage extends AbstractStorage {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private Auth auth;


    @Override
    public String upload(InputStream inputStream, String mimeType, String keyName) {
        String url = null;
        if (uploadManager == null) {
            if (auth == null) {
                auth = Auth.create(accessKey, secretKey);
            }
            uploadManager = new UploadManager(new Configuration());
        }

        try {
            String upToken = auth.uploadToken(bucketName);
            Response response = uploadManager.put(inputStream, keyName, upToken, null, mimeType);
            url = endpoint + "/" + keyName;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return url;
    }
}
